// 云函数入口文件
const cloud = require('wx-server-sdk');

// 初始化云开发环境
cloud.init();

const db = cloud.database();
const _ = db.command; // 数据库操作符

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 从 event 中获取传递的数据
    const weatherInfo = event.weatherInfo;

    // 当前时间戳（精确到当天零点，用于对比）
    const currentTimestamp = new Date(new Date().setHours(0, 0, 0, 0)).getTime();

    // 查询数据库中是否存在当天的数据
    const existingRecord = await db.collection('zyzl_weather')
      .where({
        dateTimestamp: _.eq(currentTimestamp) // 检查是否存在同一天的数据
      })
      .get();

    // 如果存在当天记录，不添加数据
    if (existingRecord.data.length > 0) {
      return {
        success: false,
        message: '当天数据已存在，无需添加'
      };
    }

    // 如果不存在当天记录，插入新数据
    const result = await db.collection('zyzl_weather').add({
      data: {
        city: weatherInfo.city,
        temp: weatherInfo.temp,
        condition: weatherInfo.condition,
        icon: weatherInfo.icon,
        windDir: weatherInfo.windDir,
        windScale: weatherInfo.windScale,
        windSpeed: weatherInfo.windSpeed,
        humidity: weatherInfo.humidity,
        tomorrowMaxTemp: weatherInfo.tomorrowMaxTemp,
        tomorrowMinTemp: weatherInfo.tomorrowMinTemp,
        tomorrowCondition: weatherInfo.tomorrowCondition,
        tomorrowIcon: weatherInfo.tomorrowIcon,
        afterdayMaxTemp: weatherInfo.afterdayMaxTemp,
        afterdayMinTemp: weatherInfo.afterdayMinTemp,
        afterdayCondition: weatherInfo.afterdayCondition,
        afterdayIcon: weatherInfo.afterdayIcon,
        dateTimestamp: currentTimestamp, // 当天零点时间戳
        createdAt: new Date() // 插入记录的时间
      }
    });

    // 返回成功结果
    return {
      success: true,
      data: result
    };
  } catch (err) {
    console.error(err);
    return {
      success: false,
      error: err
    };
  }
};
